<template>
  <div class='app-container'>
    <el-form ref='formM' :model='formM' :rules='rules'  >
      <table class='restFormTable'  border-spacing=0   >
        <tr>
           <td class='rest-tit'>
            用户
          </td>
           <td class='rest-name'>
            <el-form-item size='mini' >
              <el-input v-model='formM.companyName' :disabled="true"></el-input>
            </el-form-item>
          </td>
          <td class='rest-tit'>
            状态
          </td>
          <td class='rest-name' >
            <el-form-item size='mini' >
              <el-input v-model='formM.userState' :disabled="true"></el-input>
            </el-form-item>
          </td>
          <td width=300 rowSpan=2 style='border:0'>
            <el-button-group style='margin-left:20px'>
              <el-button  plain icon='el-icon-edit' size='mini'  @click.native.prevent="openFolder">文件夹</el-button>
              <el-button  plain icon='el-icon-tickets' size='mini' @click.native.prevent="loadFolder">读取表体</el-button>
              <el-button  icon='el-icon-printer' plain size='mini' @click.native="printRecord">打印初审</el-button>
              <el-button  plain icon='el-icon-message' size='mini' @click.native="sendEmail">发送海关</el-button>
              <el-button  plain icon='el-icon-plus' size='mini' @click.native="resetRecord" >新增</el-button>
            </el-button-group>
          </td>
        </tr>
        <tr>
          <td class='rest-tit'>
            流程编号
          </td>
          <td class='rest-input'>
             <el-form-item 
              size='mini' 
              prop='flowNo'
             >
                <el-input 
                  v-model='formM.flowNo'
                  @keyup.enter.native='vailidCode'
                ></el-input>
              </el-form-item>
          </td>
          <td  class='rest-tit'>
            收发货人
            </td>
            <td  class='rest-input'>
                 <el-select 
                  v-model='formM.businessTradeName' 
                  size='mini'  
                  filterable 
                  clearable
                  default-first-option
                  :filter-method="filterbusinessTradeName"
                  @visible-change='visibleHide("businessTradeName",$event)'
                  :popper-class='!this.focusKey.businessTradeName ? "noSelect" : ""'
                  ref="businessTradeNameRef" 
                  placeholder=''
                >
                  <el-option
                    v-for='item in shouhuoList'
                    :key='item'
                    :label='item'
                    :value='item'>
                    <div style='min-width:200px; color: #8492a6; font-size: 13px'>{{ item }}</div>
                  </el-option>
                </el-select>
            </td>
        </tr>
      </table>
      <table style='margin-top:12px'  class='restFormTable'  border-spacing=0   >
        <tr>
          <td class='rest-tit'>
            提单
          </td>
          <td class='rest-input'>
             <el-form-item 
              size='mini' 
             >
                <el-input 
                  v-model='formM.billNo'
                  ref="billNoRef" 
                  @keyup.enter.native="dealEnterCallback('mgoodsNumber', $event, 'billNo')" 
                ></el-input>
              </el-form-item>
          </td>
          <td class='rest-tit'>
            件数
          </td>
          <td class='rest-input'>
             <el-form-item 
              size='mini' 
             >
              <el-input-number 
                ref="mgoodsNumberRef" 
                @keyup.enter.native="dealEnterCallback('grossWeight', $event)" 
               v-model="formM.goodsNumber" :controls="useTool" :min="1" ></el-input-number>
              </el-form-item>
          </td>
          <td class='rest-tit'>
            毛重
          </td>
          <td class='rest-input'>
             <el-form-item 
              size='mini' 
             >
              <el-input-number 
                 ref="grossWeightRef" 
                @keyup.enter.native="dealEnterCallback('netWeight', $event)" 
               v-model="formM.grossWeight" :controls="useTool" :min="1" ></el-input-number>
              </el-form-item>
          </td>
          <td class='rest-tit'>
            净重
          </td>
          <td class='rest-input'>
             <el-form-item 
              size='mini' 
             >
              <el-input-number  
                 ref="netWeightRef" 
                @keyup.enter.native="dealEnterCallback('tradeCountry', $event)" 
               v-model="formM.netWeight" :controls="useTool" :min="0" ></el-input-number>
              </el-form-item>
          </td>
          <td class='rest-tit'>
            {{countryTxt}}
          </td>
          <td class='rest-input'>
             <el-form-item 
              size='mini' 
             >
              <el-select 
                ref="tradeCountryRef" 
                v-model='formM.tradeCountry'  
                :filter-method="filterCountrylists"
                @visible-change='visibleHide("tradeCountry",$event)'
                :popper-class='!this.focusKey.tradeCountry ? "noSelect" : ""'
                filterable 
                clearable
                default-first-option
                placeholder=''
              >
                <el-option
                  v-for='item in countrylists'
                  :key='item._id'
                  :label='item.name'
                  :value='item.code'>
                  <span class="sel-labelleft">{{ item.code }}</span>
                  <span class="sel-labelright">{{ item.name }}</span>
                </el-option>
              </el-select>
              </el-form-item>
          </td>
        </tr>
    </table>
    </el-form>
    
    <el-table  
      height='258' 
      :data='list' 
      v-loading.body='listLoading' 
      element-loading-text='Loading' 
      border  
      cell-class-name="nowrap"
      highlight-current-row
      ref="dataTable"  
      style="width:95%"
      empty-text= ' '
      @selection-change="handleSelectionChange"
      @cell-click = "handleCellClick"
    >
      <el-table-column
        type='selection'
        width='30'>
      </el-table-column>
      <el-table-column align='left' fixed label='序号' min-width='35'>
        <template slot-scope='scope'>
          {{scope.row.goodsNo}}
        </template>
      </el-table-column>
      <el-table-column align='left' fixed label='商品编号' min-width='100'>
        <template slot-scope='scope'>
          <span :title='scope.row.goodsHsCode'>{{scope.row.goodsHsCode}}</span>
        </template>
      </el-table-column>
      <el-table-column align='left' label='商品名称' min-width='200'>
            <template slot-scope='scope'>
              <span :title='scope.row.goodsCnName'>{{scope.row.goodsCnName}}</span>
            </template>
      </el-table-column>
      <el-table-column align='left' label='规格' min-width='200'>
        <template slot-scope='scope'>
          <span :title='scope.row.goodsModel'>{{scope.row.goodsModel}}</span>
        </template>
      </el-table-column>
      <el-table-column align='left' label='原产国' min-width='70'>
        <template slot-scope='scope'>
          <span :title='scope.row.originCodeName'>{{scope.row.originCodeName}}</span>
        </template>
      </el-table-column>
      <el-table-column align='left' label='数量' min-width='76'>
        <template slot-scope='scope'>
          {{scope.row.quantity  || 0}}
        </template>
      </el-table-column>
      <el-table-column align='left' label='单位' min-width='76'>
        <template slot-scope='scope'>
          {{scope.row.quantityUnitName}}
        </template>
      </el-table-column>
      <el-table-column align='left' label='单价' min-width='76'>
        <template slot-scope='scope'>
          {{scope.row.unitPrice  || 0}}
        </template>
      </el-table-column>
      <el-table-column align='left' label='币制' min-width='70'>
        <template slot-scope='scope'>
          {{scope.row.currencyName}}
        </template>
      </el-table-column>
      <el-table-column align='left' label='总价' min-width='76'>
        <template slot-scope='scope'>
          {{scope.row.totalPrice || 0}}
        </template>
      </el-table-column>
      <el-table-column align='left' label='征免' min-width='120'>
        <template slot-scope='scope'>
          {{scope.row.dutyModeName}}
        </template>
      </el-table-column>
      <el-table-column align='left' label='最终目的国' min-width='105'>
        <template slot-scope='scope'>
          <span :title='scope.row.destinationCountryName'>{{scope.row.destinationCountryName}}</span>
        </template>
      </el-table-column>
      <el-table-column align='left' label='境内货源地' min-width='105'>
        <template slot-scope='scope'>
          <span :title='scope.row.destinationAreaName'>{{scope.row.destinationAreaName}}</span>
        </template>
      </el-table-column>
      <el-table-column align='left' label='境内原产地' min-width='105'>
        <template slot-scope='scope'>
          <span :title='scope.row.destinationDetailAreaName'>{{scope.row.destinationDetailAreaName}}</span>
        </template>
      </el-table-column>
      <el-table-column align='left'  label='备案序号' min-width='76'>
        <template slot-scope='scope'>
          {{scope.row.recordNo}}
        </template>
      </el-table-column>
      <el-table-column align='left' label='危险品' min-width='76'>
        <template slot-scope='scope'>
          {{scope.row.danger}}
        </template>
      </el-table-column>
      <el-table-column align='left' label='监管条件' min-width='76'>
        <template slot-scope='scope'>
          {{scope.row.supervise}}
        </template>
      </el-table-column>
    </el-table>
    <el-row>
      <el-tooltip content="新增" placement="top" effect="light">
        <i class='el-icon-plus' @click="operList('add')"></i>
      </el-tooltip>
      <el-tooltip content="删除" placement="top" effect="light">
        <i class='el-icon-delete' @click="operList('del')"></i>
      </el-tooltip>
      <el-tooltip content="复制" placement="top" effect="light">
        <i class='el-icon-document-copy' @click="operList('copy')"></i>
      </el-tooltip>
      <el-tooltip content="插入" placement="top" effect="light">
        <i class='el-icon-news' @click="operList('insert')"></i>
      </el-tooltip>
      <el-tooltip content="上移" placement="top" effect="light">
        <i class='el-icon-arrow-up' @click="operList('up')"></i>
      </el-tooltip>
      <el-tooltip content="下移" placement="top" effect="light">
        <i class='el-icon-arrow-down' @click="operList('down')"></i>
      </el-tooltip>
      <el-tooltip content="批量编辑" placement="top" effect="light">
        <i class='el-icon-edit' @click="operList('bat')" ></i>
      </el-tooltip>
      <el-tooltip content="保存" placement="top" effect="light">
        <i class='el-icon-circle-plus-outline' @click="addRecord" ></i>
      </el-tooltip>
    </el-row>
    <table class='restFormTable'  border-spacing=0   >
      <tr>
          <td class='rest-tit left'>
            表头毛重：<span class="td-value">{{formM.grossWeight || 0}}</span>
          </td>
          <td class='rest-tit left'>
            表头净重：<span class="td-value">{{allWeight}}</span>
          </td>
         <td class='rest-tit left'>
            表头件数：<span class="td-value">{{formM.goodsNumber || 0}}</span>
          </td>
          <td class='rest-tit left'>
            {{countryTxt}}：<span class="td-value">{{formM.tradeCountry || ''}}</span>
          </td>
      </tr>
      <tr>
          <td class='rest-tit left'>
            总价汇总：<span class="td-value">{{allTotalPrice}}</span>
          </td>
          <td class='rest-tit left'>
            重量汇总：<span class="td-value">{{allWeight}}</span>
          </td>
         <td class='rest-tit left'>
            成交数量汇总：<span class="td-value">{{allNumPrice}}</span>
          </td>
          <td class='rest-tit left'>
          需法检货物数量：<span class="td-value">0 项</span>
          </td>
      </tr>
    </table>
    <el-form ref='form' :model='form' :rules='rules'>
    <table 
      class='restFormTable'  
      border-spacing=0  
    >
      <tr>
        <td class='rest-tit'>
          商品序号
        </td>
        <td class='rest-name'>
            <el-form-item size='mini' >
              <el-input v-model='form.goodsNo' :disabled="true"></el-input>
            </el-form-item>
        </td>
        
         <td class='rest-tit'>
          商品编码
        </td>
        <td class='rest-input'>
            <RemoteSelect 
              @combineSelect="combineSelect"
              @dealEnterCallback="dealEnterCallback"
              @searchShopCode="searchShopCode"
              @hideOtherWin='hideOtherWin'
              :tool="true"
              :isSetting = "isSetting"
              :formData.sync="form"
              ref="goodsHsCode"
              :formObj="remoteConfig[1]"
           />
        </td>
        <td class='rest-tit'>
          检验/疫码
        </td>
        <td class='rest-input'>
          <el-form-item size='mini' >
            <el-input v-model='form.recordNo' :disabled="true"></el-input>
          </el-form-item>
        </td>
        <td class='rest-tit'>
          危险品
        </td>
        <td class='rest-name'>
          <el-form-item size='mini' >
            <el-input v-model='form.danger' :disabled="true"></el-input>
          </el-form-item>
        </td>
         <td class='rest-tit'>
          监管条件
        </td>
        <td class='rest-name'>
          <el-form-item size='mini' >
            <el-input v-model='form.supervise' :disabled="true"></el-input>
          </el-form-item>
        </td>
      </tr>
      <tr>
        <td class='rest-tit'>
          商品名称
        </td>
        <td class='rest-input' colSpan='3'>
           <RemoteSelect 
              @combineSelect="combineSelect"
              @dealEnterCallback="dealEnterCallback"
              @hideOtherWin='hideOtherWin'
              :formData.sync="form"
              ref="goodsCnName"
              :isSetting = "isSetting"
              :formObj="remoteConfig[0]"
           />
        </td>
         <td class='rest-tit'>
          规格型号
        </td>
        <td class='rest-input'  colSpan='5'>
            <RemoteSelect 
              @combineSelect="combineSelect"
              @dealEnterCallback="dealEnterCallback"
              @searchShopCode="searchShopCode"
              @hideOtherWin='hideOtherWin'
              :tool="true"
              :formData.sync="form"
              :isSetting = "isSetting"
              ref="goodsModel"
              :formObj="remoteConfig[2]"
           />
        </td>
      </tr>
      <tr>
       <td class='rest-tit'>
          成交数量
        </td>
        <td class='rest-input'  >
            <el-form-item size='mini' >
              <el-input-number ref="quantityRef" @keyup.enter.native="dealEnterCallback('quantityUnit', $event)" @blur="changePrice('quantity')" v-model="form.quantity" :controls="useTool" :min="1" ></el-input-number>
            </el-form-item>
        </td>
        <td class='rest-tit'>
          成交单位
        </td>
        <td class='rest-input'  >
            <el-form-item size='mini' >
              <el-select
                ref="quantityUnitRef" 
                @keyup.enter.native="dealEnterCallback('unitPrice', $event, 'quantityUnit')" 
                v-model='form.quantityUnit'  
                filterable 
                clearable
                @change='getSelectValue("quantityUnit",unitlists,$event)'
                :filter-method="selectFilter"
                @visible-change='visibleHide("quantityUnit",$event)'
                :popper-class='!this.focusKey.quantityUnit ? "noSelect" : ""'
                placeholder=''>
                <el-option
                  v-for='item in unitlists'
                  :key='item.code'
                  :label='item.name'
                  :value='item.code'>
                  <span class="sel-labelleft">{{ item.code }}</span>
                  <span class="sel-labelright">{{ item.name }}</span>
                </el-option>
              </el-select>
            </el-form-item>
        </td>
        <td class='rest-tit'>
          单价
        </td>
        <td class='rest-input'  >
            <el-form-item size='mini' >
              <el-input-number ref="unitPriceRef" @keyup.enter.native="dealEnterCallback('totalPrice', $event)"  @blur="changePrice('unitPrice')" v-model="form.unitPrice" :controls="useTool" :precision="4"  :min="0" :step="0.1" ></el-input-number>
            </el-form-item>
        </td>
        <td class='rest-tit'>
          总价
        </td>
        <td class='rest-input'  >
            <el-form-item size='mini' >
              <el-input-number ref="totalPriceRef" @keyup.enter.native="dealEnterCallback('currency', $event)"  @blur="changePrice('totalPrice')" v-model="form.totalPrice" :controls="useTool" :precision="2" :min="0" :step="0.1" ></el-input-number>
            </el-form-item>
        </td>
        <td class='rest-tit'>
          币制
        </td>
        <td class='rest-input'  >
            <el-form-item size='mini' >
              <el-select 
                ref="currencyRef" 
                default-first-option
                @keyup.enter.native="dealEnterCallback('firstQuantity', $event, 'currency')" 
                @change='getSelectValue("currency",bilists,$event)'
                v-model='form.currency'
                :filter-method="selectFilter"
                @visible-change='visibleHide("currency",$event)'
                :popper-class='!this.focusKey.currency ? "noSelect" : ""'
                filterable 
                clearable
               >
                <el-option
                  v-for='item in bilists'
                  :key='item._id'
                  :label='item.name'
                  :value='item.code'>
                   <span class="sel-labelleft">{{ item.code }}</span>
                  <span class="sel-labelright">{{ item.name }}</span>
                </el-option>
              </el-select>
            </el-form-item>
        </td>
      </tr>
      <tr>
         <td class='rest-tit'>
            法定数量
          </td>
          <td class='rest-input'  >
              <el-form-item size='mini' >
                <el-input-number ref="firstQuantityRef" @keyup.enter.native="dealEnterCallback('version', $event)" v-model="form.firstQuantity" :controls="useTool" :min="1" ></el-input-number>
              </el-form-item>
          </td>
          <td class='rest-tit'>
            法定单位
          </td>
          <td class='rest-input'  >
              <el-form-item size='mini' >
                <el-select 
                  v-model='form.firstUnit' 
                  clearable
                  :disabled="true" 
                  >
                  <el-option
                    v-for='item in unitlists'
                    :key='item._id'
                    :label='item.name'
                    :value='item.code'>
                     <span class="sel-labelleft">{{ item.code }}</span>
                     <span class="sel-labelright">{{ item.name }}</span>
                  </el-option>
                </el-select>
              </el-form-item>
          </td>
          <td class='rest-tit'>
            版本号
          </td>
          <td class='rest-input'  >
              <el-form-item size='mini' >
                <el-input v-model='form.version' ref="versionRef" @keyup.enter.native="dealEnterCallback('goodsNumber', $event)"></el-input>
              </el-form-item>
          </td>
          <td class='rest-tit'>
            货号
          </td>
          <td class='rest-input'  >
            <el-form-item size='mini' >
              <el-input v-model='form.goodsNumber' ref="goodsNumberRef" @keyup.enter.native="dealEnterCallback('destinationCountry', $event)"></el-input>
            </el-form-item>
          </td>
          <td class='rest-tit'>
            最终目的国
          </td>
          <td class='rest-input'  >
            <el-form-item size='mini' >
              <el-select 
                ref="destinationCountryRef" 
                @keyup.enter.native="dealEnterCallback('secondQuantity', $event, 'destinationCountry')" 
                @change='getSelectValue("destinationCountry",countrylists1,$event)'
                v-model='form.destinationCountry'  
                :filter-method="selectFilter"
                @visible-change='visibleHide("destinationCountry",$event)'
                :popper-class='!this.focusKey.destinationCountry ? "noSelect" : ""'
                filterable 
                clearable
                default-first-option
                >
                <el-option
                  v-for='item in countrylists1'
                  :key='item._id'
                  :label='item.name'
                  :value='item.code'>
                  <span class="sel-labelleft">{{ item.code }}</span>
                  <span class="sel-labelright">{{ item.name }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </td>
      </tr>
      <tr>
        <td class='rest-tit'>
            第二数量
          </td>
          <td class='rest-input'  >
              <el-form-item size='mini' >
                <el-input-number :disabled="!form.secondUnit" ref="secondQuantityRef" @keyup.enter.native="dealEnterCallback('originCode', $event)" v-model="form.secondQuantity" :controls="useTool" :min="1" ></el-input-number>
              </el-form-item>
          </td>
          <td class='rest-tit'>
            第二单位
          </td>
          <td class='rest-input'  >
              <el-form-item size='mini' >
                <el-select 
                  v-model='form.secondUnit' 
                  clearable
                  :disabled="true" 
                  >
                  <el-option
                    v-for='item in unitlists'
                    :key='item._id'
                    :label='item.name'
                    :value='item.code'>
                   <span class="sel-labelleft">{{ item.code }}</span>
                  <span class="sel-labelright">{{ item.name }}</span>
                  </el-option>
                </el-select>
              </el-form-item>
          </td>
          <td class='rest-tit' colSpan="2">
            原产国(地区)
          </td>
          <td class='rest-input' colSpan='4' >
              <el-form-item size='mini' >
                <el-select  
                  ref="originCodeRef" 
                  @keyup.enter.native="dealEnterCallback('destinationArea', $event, 'originCode')" 
                  @change='getSelectValue("originCode",countrylists2,$event)'
                  v-model='form.originCode'   
                  :filter-method="selectFilter"
                  @visible-change='visibleHide("originCode",$event)'
                  :popper-class='!this.focusKey.originCode ? "noSelect" : ""'
                  filterable 
                  clearable
                  default-first-option
                  >
                  <el-option
                    v-for='item in countrylists2'
                    :key='item.code'
                    :label='item.name'
                    :value='item.code'>
                   <span class="sel-labelleft">{{ item.code }}</span>
                    <span class="sel-labelright">{{ item.name }}</span>
                  </el-option>
                </el-select>
              </el-form-item>
          </td>
      </tr>
      <tr>
          <td class='rest-tit'>
            境内货源地
          </td>
          <td class='rest-input'  >
              <el-form-item size='mini' >
                <el-select 
                  ref="destinationAreaRef" 
                  @keyup.enter.native="dealEnterCallback('destinationDetailArea', $event, 'destinationArea')" 
                  v-model='form.destinationArea'
                  @change='getSelectValue("destinationArea",huoResLists,$event)'
                  :filter-method="selectFilter"
                  @visible-change='visibleHide("destinationArea",$event)'
                  :popper-class='!this.focusKey.destinationArea ? "noSelect" : ""'
                  filterable 
                  clearable
                  default-first-option
                  >
                  <el-option
                    v-for='item in huoResLists'
                    :key='item._id'
                    :label='item.name'
                    :value='item.code'>
                   <span class="sel-labelleft">{{ item.code }}</span>
                  <span class="sel-labelright">{{ item.name }}</span>
                  </el-option>
                </el-select>
              </el-form-item>
          </td>
          <td class='rest-input'  >
              <el-form-item size='mini' >
                <el-select 
                  ref="destinationDetailAreaRef" 
                  @keyup.enter.native="dealEnterCallback('dutyMode', $event, 'destinationDetailArea')" 
                  v-model='form.destinationDetailArea' 
                  @change='getSelectValue("destinationDetailArea",citiesList,$event)'
                  :filter-method="selectFilter"
                  @visible-change='visibleHide("destinationDetailArea",$event)'
                  :popper-class='!this.focusKey.destinationDetailArea ? "noSelect" : ""'
                  filterable 
                  clearable
                  default-first-option
                  >
                  <el-option
                    v-for='item in citiesList'
                    :key='item._id'
                    :label='item.name'
                    :value='item.code'>
                    <span class="sel-labelleft">{{ item.code }}</span>
                  <span class="sel-labelright">{{ item.name }}</span>
                  </el-option>
                </el-select>
              </el-form-item>
          </td>
          <td class='rest-tit'>
            征免
          </td>
          <td class='rest-input'  >
              <el-form-item size='mini' >
                <el-select 
                  ref="dutyModeRef"  
                  v-model='form.dutyMode' 
                  @keyup.enter.native='addRecord'  
                  @change='getSelectValue("dutyMode",mianLists,$event)'
                  @visible-change='visibleHide("dutyMode",$event)'
                  :popper-class='!this.focusKey.dutyMode ? "noSelect" : ""'
                  :filter-method="selectFilter"
                  filterable 
                  clearable
                  default-first-option
                  >
                  <el-option
                    v-for='item in mianLists'
                    :key='item._id'
                    :label='item.name'
                    :value='item.code'>
                    <span class="sel-labelleft">{{ item.code }}</span>
                    <span class="sel-labelright">{{ item.name }}</span>
                  </el-option>
                </el-select>
              </el-form-item>
          </td>
          <td colSpan='5'>
              <el-button-group style='margin-left:20px'>
                <el-button @click="navList('first')"  plain icon='el-icon-d-arrow-left' size='mini'>第一条</el-button>
                <el-button  @click="navList('prev')" plain icon='el-icon-arrow-left' size='mini'>上一条</el-button>
                <el-button  @click="navList('next')" plain icon='el-icon-arrow-right' size='mini'>下一条</el-button>
                <el-button  @click="navList('last')" icon='el-icon-d-arrow-right' plain  size='mini'>最后一条</el-button>
              </el-button-group>
          </td>
      </tr>
    </table>
    </el-form>
    <GetCode 
      :invitor="isShow" 
      :goodNo="form.goodsHsCode"
      @changingType="showlDialog" 
      @combineSelect="combineSelect" 
    ></GetCode>
    <GetInfo 
      :invitor="showInfo" 
      :brands="brands" 
      :precents="precents" 
      :goodsModel="form.goodsModel" 
      :goodNo="form.goodsHsCode"
      @dealEnterCallback="dealEnterCallback"
      @changingType="showlDialog"  
      @combineSelect="combineSelect" 
    ></GetInfo>
    <BatWin 
      :invitor="batShow"
      :brands="brands" 
      :precents="precents"  
      :citiesList="citiesListCopy" 
      :huoResLists="huoResListsCopy" 
      :mianLists="mianListsCopy" 
      :bilists="bilistsCopy"  
      :countrylists="countrylistsCopy" 
      @changingType="batOper" 
    ></BatWin>
    <el-dialog
      title="提示"
      :visible.sync="centerDialogVisible"
      width="30%"
      center>
      <div style="margin-bottom:20px;text-align:center">数量已修改，是否修改价格？</div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary"  size="mini"  @click="changePrice('changeprice')">修改单价</el-button>
        <el-button type="primary"  size="mini"  @click="changePrice('changetotalPrice')">修改总价</el-button>
        <el-button size="mini" @click="centerDialogVisible = false" >取 消</el-button>
      </span>
    </el-dialog>
    <!-- 打印模版引入 -->
    <webview style="position:absolute;left:-3000px;top:-3000px;" id="webPrint" src="../../../static/print.html" nodeintegration ></webview>
  </div>
</template>

<script>

import { queryFlowInfo, queryEntryDeta, querFlowInfoBy, autoCheck, generateMessage } from '@/api/entering'
import { getDicture, queryAllInfo } from '@/api/login'
import store from '@/store/index'
import GetCode from './components/GetCode.vue'
import GetInfo from './components/GetInfo.vue'
import BatWin from './components/BatWin.vue'
const path = require('path')
const { shell, ipcRenderer } = require('electron')
import { parseFile } from '@/utils/parseExcel'
import RemoteSelect from './components/RemoteSelect.vue'
export default {
  components: {
    GetCode,
    GetInfo,
    BatWin,
    RemoteSelect
  },
  data() {
    return {
      list: [],
      listLoading: false,
      useTool: false,
      isShow: false,
      showInfo: false,
      batShow: false,
      isSetting: false, // 设置中
      countryTxt: '运抵国/地区',
      multipleSelection: [],
      countrylists: [],
      countrylistsCopy: [],
      countrylists1: [],
      countrylists2: [],
      loading: false,
      unitlists: [],
      unitlistsCopy: [],
      bilists: [],
      bilistsCopy: [],
      mianLists: [],
      mianListsCopy: [],
      goodsHsCodeState: false,
      huoResLists: [],
      huoResListsCopy: [],
      citiesList: [],
      citiesListCopy: [],
      shouhuoList: [],
      shouhuoListCopy: [],
      focusKey: {},
      remoteConfig: [{
        key: 'goodsCnName',
        next: 'goodsHsCode'
      }, {
        key: 'goodsHsCode',
        next: 'goodsModel'
      }, {
        key: 'goodsModel',
        next: 'quantity'
      }],
      brands: ['无品牌', '境内自主品牌', '境内收购品牌', '境外品牌（贴牌生产）', '境外品牌（其他）'],
      precents: ['出口货物在最终目的国不享惠', '出口货物在最终目的国享受优惠关税', '生产销售单位尚未确定货物享惠情况', '不适用于进口报关单'],
      centerDialogVisible: false,
      pathUrl: store.getters.path,
      form: {
        goodsNo: 1
      },
      formM: {
        flowNo: ''
      },
      rules: {
        flowNo: [
          { required: true, message: '请输入流程编码', trigger: 'blur' },
          { min: 13, max: 13, message: '请输入13个字符', trigger: 'change' }
        ]
      }
    }
  },
  watch: {
    form: {
      deep: true,
      handler(val = {}, next = {}) {
        const compareArr = ['quantityUnit', 'currency', 'destinationArea', 'destinationCountry', 'destinationDetailArea', 'dutyMode', 'originCode']
        compareArr.map(item => {
          if (val[item] && (val[item] !== next[item])) {
            this.selectFilter(val[item], false, item)
          }
        })
      }
    }
  },
  computed: {
    goodsCnName() {
      return this.form.goodsCnName
    },
    allTotalPrice() {
      let sum = 0
      this.list.map(item => {
        sum += item.totalPrice || 0
      })
      return parseFloat(sum).toFixed(3)
    },
    allNumPrice() {
      let sum = 0
      this.list.map(item => {
        sum += item.quantity || 0
      })
      return sum
    },
    allWeight() {
      let sum = 0
      this.list.map(item => {
        if (item.quantityUnit === '035') {
          sum += item.quantity || 0
        } else if (item.firstUnit === '035') {
          sum += item.firstQuantity || 0
        } else if (item.secondUnit === '035') {
          sum += item.secondQuantity || 0
        }
      })
      sum = parseFloat(sum).toFixed(3)
      this.formM.netWeight = sum
      return sum
    }
  },
  mounted() {
    this.initPrint()
    getDicture().then(response => {
      Object.entries(response).map(item => {
        const [key, value] = item
        this.$db[key].find({}).exec((err2, docs) => {
          if (!docs.length) {
            this.$db[key].insert(value)
          }
        })
      })
    })
    queryAllInfo().then(response => {
      this.$db.goodsData.find({}).exec((err2, docs) => {
        if (!docs.length) {
          this.$db.goodsData.insert(response)
        }
      })
    })
    const postArr = [
      this.findDictDataByFilter('102'),
      this.findDictDataByFilter('1'),
      this.findDictDataByFilter('3'),
      this.findDictDataByFilter('103'),
      this.findDictDataByFilter('105'),
      this.findDictDataByFilter('2')
    ]
    Promise.all(postArr).then((result) => {
      const [{ data: citiesList }, { data: unitlists }, { data: bilists }, { data: mianLists }, { data: huoResLists }, { data: countrylists }] = result
      this.citiesList = citiesList
      this.citiesListCopy = Object.assign(citiesList)
      this.unitlists = unitlists
      this.unitlistsCopy = Object.assign(unitlists)
      this.bilists = bilists
      this.bilistsCopy = Object.assign(bilists)
      this.mianLists = mianLists
      this.mianListsCopy = Object.assign(mianLists)
      this.huoResLists = huoResLists
      this.huoResListsCopy = Object.assign(huoResLists)
      this.countrylists = countrylists
      this.countrylists1 = Object.assign(countrylists)
      this.countrylists2 = Object.assign(countrylists)
      this.countrylistsCopy = Object.assign(countrylists)
    }).catch(() => {
    })
  },
  methods: {
    getSelectValue(type, list, value) {
      //  如果当前为出口 最终目的国 得值要重置表头
      if (type === 'destinationCountry' && this.formM.userState === '出口') {
        this.formM.tradeCountry = value
      }
      this.form[type + 'Name'] = list.find(item => {
        return item.code === value
      }).name
    },
    combineSelect(data) {
      this.form = Object.assign({}, this.form, data)
      this.settingStatus()
    },
    //  阻止二次渲染下拉框
    settingStatus() {
      this.isSetting = true
      setTimeout(() => {
        this.isSetting = false
      }, 3000)
    },
    openFolder() {
      const openPath = path.join(this.pathUrl, this.formM.flowNo + '\\*')
      shell.showItemInFolder(openPath)
    },
    loadFolder: async function() {
      const loading = this.getLoadingMask('读取表体中，请稍后！')
      const list = await parseFile(`${this.pathUrl}/标准报关资料.xls`, this.$db, this.bilistsCopy, this.unitlistsCopy, this.mianListsCopy)
      list.splice(0, 1)
      this.list = list
      loading.close()
    },
    navList(type) {
      const data = this.list
      const curForm = this.form
      if (type === 'first') {
        this.form = data[0]
      } else if (type === 'prev' || type === 'next') {
        const goodsNo = curForm.goodsNo
        const len = data.length
        let dest = 0
        if (type === 'prev') {
          dest = goodsNo - 1 < 1 ? 1 : goodsNo - 1
        } else {
          dest = goodsNo + 1 > len ? len : goodsNo + 1
        }
        const index = data.findIndex(item => item.goodsNo === dest)
        this.form = data[index]
      } else if (type === 'last') {
        this.form = data[data.length - 1]
      }
      this.$refs.dataTable.setCurrentRow(this.form)
      this.cellClickRow = this.form
    },
    operList(type) {
      if (type === 'add') {
        this.form = {
          goodsNo: this.list.length + 1
        }
      } else if (type === 'del' || type === 'bat') {
        if (!!this.multipleSelection && !!this.multipleSelection.length) {
          if (type === 'del') {
            this.$confirm('确定删除?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              const delteKey = this.multipleSelection.map(item => item.goodsNo)
              const arr = []
              this.list.map(item => {
                if (!delteKey.includes(item.goodsNo)) {
                  item.goodsNo = arr.length + 1
                  arr.push(item)
                }
              })
              this.list = arr
              this.$message({
                message: '删除成功',
                type: 'success',
                center: true
              })
            })
          } else if (type === 'bat') {
            this.searchShopCode('batShow')
          }
        } else {
          this.$message({
            message: type === 'bat' ? '请选择要操作的项' : '请选择要删除的项',
            type: 'warning',
            center: true
          })
        }
      } else if (type === 'copy' || type === 'up' || type === 'down' || type === 'insert') {
        if (this.cellClickRow) {
          if (type === 'copy') {
            const row = Object.assign({}, this.cellClickRow)
            row.goodsNo = this.list.length + 1
            this.list.push(row)
          } else if (type === 'insert') {
            const index = this.list.findIndex(item => item.goodsNo === this.cellClickRow.goodsNo)
            this.list.splice(index + 1, 0, {})
            this.list = this.resetIndex(this.list)
          } else {
            const index = this.list.findIndex(item => item.goodsNo === this.cellClickRow.goodsNo)
            const len = this.list.length
            let dest = 0
            if (type === 'up') {
              dest = index - 1
              if (dest < 0) {
                dest = 0
              }
            } else {
              dest = index + 1
              if (dest > len - 1) {
                dest = len - 1
              }
            }
            if (dest !== index) {
              this.list = this.swapArr(this.list, index, dest)
              this.list = this.resetIndex(this.list)
            }
          }
        } else {
          this.$message({
            message: '请选择要操作的项',
            type: 'warning',
            center: true
          })
        }
      }
    },
    // price 逻辑
    changePrice(type) {
      const {
        quantity,
        unitPrice,
        totalPrice
      } = this.form
      if (type === 'quantity') {
        if (totalPrice) {
          this.centerDialogVisible = true
        }
      } else if (type === 'unitPrice' || type === 'changetotalPrice') {
        this.form.totalPrice = unitPrice * quantity
      } else if (type === 'totalPrice' || type === 'changeprice') {
        this.form.unitPrice = totalPrice / quantity
      }
      if (['changeprice', 'changetotalPrice'].includes(type)) {
        this.centerDialogVisible = false
      }
    },
    resetIndex(arr) {
      arr.map((item, index) => {
        item.goodsNo = index + 1
      })
      return arr
    },
    swapArr(arr, index1, index2) {
      arr[index1] = arr.splice(index2, 1, arr[index1])[0]
      return arr
    },
    handleCellClick(row) {
      this.cellClickRow = row
      this.form = Object.assign({}, row)
      this.$refs.dataTable.clearSelection() //  清空所有选择
      this.$refs.dataTable.toggleRowSelection(row) //  选中当前选择
    },
    handleSelectionChange(rows) {
      this.multipleSelection = rows
    },
    deepClone(obj) {
      return JSON.parse(JSON.stringify(obj))
    },
    addRecord() {
      this.$refs.form.validate((valid, values) => {
        if (Object.keys(this.form).length < 2) {
          this.$message({
            message: '填写完整后添加',
            type: 'warning',
            center: true
          })
        } else {
          const row = this.form
          const list = this.list
          if (row.goodsNo <= list.length) {
            const index = list.findIndex(item => item.goodsNo === row.goodsNo)
            list[index] = row
            this.list = this.deepClone(list)
          } else {
            this.list.push({
              ...this.form,
              ciqCode: '', //  TODO预留 ciqCode ciqName 两个字段
              ciqName: ''
            })
          }
          console.log(this.list)
          this.$refs.dutyModeRef.blur()
          this.$refs.goodsCnName.$refs.goodsCnNameRef.focus()
          this.form = {
            goodsNo: this.list.length + 1
          }
        }
      })
    },
    hideOtherWin(key) {
      const keyArr = ['goodsCnName', 'goodsHsCode', 'goodsModel']
      keyArr.map(item => {
        if (key !== item) {
          this.$refs[item].closeWin()
        }
      })
    },
    vailidCode(e) {
      const value = e.target.value
      if (value.length === 13) {
        querFlowInfoBy(value).then(res => {
          this.formM.billNo = res.billNo
          this.formM.goodsNumber = res.goodsNumber
          this.formM.grossWeight = res.grossWeight
        })
        queryFlowInfo(value).then(response => {
          const {
            data
          } = response
          const {
            flowType,
            companyName,
            companyCode,
            sccCode
          } = data
          this.formM = {
            ...this.formM,
            companyName,
            companyCode,
            companyScc: sccCode,
            userState: flowType === 0 ? '出口' : '进口',
            flowType,
            countryTxt: flowType === 0 ? '运抵国/地区' : '起运国/地区'
          }
          queryEntryDeta(data.sccCode).then(response => {
            this.$db.companyData.remove({}, { multi: true })
            this.shouhuoListCopy = Array.from(new Set(response.data.map(item => item.businessTradeName)))
            this.shouhuoList = JSON.parse(JSON.stringify(this.shouhuoListCopy))
            this.$db.companyData.insert(response.data)
            this.$refs.businessTradeNameRef.focus()
          })
        })
      }
    },
    searchShopCode(type = 'isShow') {
      this.showlDialog(true, type)
    },
    //  回车事件走的效果
    dealEnterCallback(type, event, curType) {
      if (type === 'quantityUnit') {
        // 如果法定单位 和 成交单位一致 则 法定和成交一样  新增需求
        if (this.form.quantityUnit === this.form.firstUnit) {
          this.form.firstQuantity = this.form.quantity
        }
      }
      if (type === 'secondQuantity') {
        if (this.formM.userState === '出口') {
          this.formM.tradeCountry = this.form.destinationCountry
        }
      }
      this.$nextTick(() => {
        let dest
        if (this.$refs[type]) {
          dest = this.$refs[type].$refs[type + 'Ref']
        } else {
          if (!this.form.secondUnit && type === 'secondQuantity') {
            dest = this.$refs.originCodeRef
          } else {
            dest = this.$refs[type + 'Ref']
          }
        }
        if (curType && this.$refs[curType + 'Ref']) {
          this.$refs[curType + 'Ref'].blur()
        }
        dest.focus()
      })
    },
    //  显示隐藏的坐标限制
    visibleHide(type, value) {
      if (!value) {
        this.focusKey[type] = false
        this.focusKey = Object.assign({}, this.focusKey)
      } else {
        this.curSel = type
      }
    },
    //  对运送国进行过滤
    filterCountrylists(value) {
      this.focusKey.tradeCountry = true
      this.countrylists = this.countrylistsCopy.filter(item => {
        return this.itemVaild(item, value)
      })
    },
    //  对收发货人进行过滤
    filterbusinessTradeName(value) {
      this.focusKey.businessTradeName = true
      this.shouhuoList = this.shouhuoListCopy.filter(item => {
        if (item.indexOf(value.toUpperCase()) !== -1) {
          return true
        } else {
          return false
        }
      })
    },
    //  过滤函数
    selectFilter(value, flag = true, type = '') {
      const key = type || this.curSel
      const _table = {
        quantityUnit: 'unitlists',
        originCode: 'countrylists',
        destinationCountry: 'countrylists',
        currency: 'bilists',
        dutyMode: 'mianLists',
        destinationArea: 'huoResLists',
        destinationDetailArea: 'citiesList'
      }
      let _dest = _table[key]
      // 一些特殊的key 处理
      if (key === 'originCode') {
        _dest += '2'
      } else if (key === 'destinationCountry') {
        _dest += '1'
      }
      if (flag) {
        this.focusKey[key] = true
      }
      this[_dest] = this[_table[key] + 'Copy'].filter(item => {
        return this.itemVaild(item, value)
      })
    },
    itemVaild(item, value = '') {
      if (item.code.indexOf(value.toUpperCase()) !== -1 || item.name.indexOf(value) !== -1) {
        return true
      } else {
        return false
      }
    },
    // 根据数据字典过滤数据
    findDictDataByFilter(type = 1, filterOb = {}) {
      return new Promise((resolve) => {
        this.$db['DECLARE_DICT_' + type].find(filterOb).sort({ code: 1 }).exec((err, docs) => {
          resolve({
            data: docs,
            err
          })
        })
      })
    },
    showlDialog(data, type = 'isShow') {
      if (data === 'false') {
        this[type] = false
      } else {
        this[type] = true
      }
    },
    batOper(data, type, formData, goodsModelPre) {
      this[type] = false
      if (data) {
        const {
          checkNull,
          ..._formData
        } = formData
        if (checkNull) {
          //  只修改空的
          this.list = this.list.map((item, index) => {
            const goodsModel = !item.goodsModel ? [] : item.goodsModel.split('|')
            goodsModel[0] = goodsModelPre[0]
            goodsModel[1] = goodsModelPre[1]
            Object.entries(_formData).map(_item => {
              const [key, value] = _item
              item[key] = !item[key] ? value : item[key]
            })
            item.goodsModel = goodsModel.join('|')
            return item
          })
        } else {
          //  全部替换
          this.list = this.list.map(item => {
            const goodsModel = !item.goodsModel ? [] : item.goodsModel.split('|')
            goodsModel[0] = goodsModelPre[0]
            goodsModel[1] = goodsModelPre[1]
            item = { ...item, ..._formData, goodsModel: goodsModel.join('|') }
            return item
          })
        }
      }
    },
    resetRecord() {
      this.$confirm('确定新增?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.form = {
          goodsNo: 1
        }
        this.formM = {}
        this.list = []
      })
    },
    initPrint() {
      // 渲染线程主动发送 getPrinterList 事件到主线程请求打印机列表
      ipcRenderer.send('getPrinterList')
      // 监听主线程获取到打印机列表后的回调
      ipcRenderer.once('getPrinterList', (event, data) => {
        // data就是打印机列表
        console.log('打印机列表：', data)
        this.deviceName = (data[2] && data[2].name) || ''
      })
      const webPrint = document.querySelector('webview')
      webPrint.addEventListener('ipc-message', (event) => {
        if (event.channel === 'webview-print-do') {
          webPrint.print({
            //  是否是静默打印,true为静默打印，false会弹出打印设置框
            silent: false,
            printBackground: true,
            deviceName: this.deviceName
          }, (data) => {
            if (data) {
              this.$message({
                message: '打印成功',
                type: 'success',
                center: true
              })
            }
          })
        }
      })
    },
    printRecord() {
      const webPrint = document.querySelector('webview')
      this.$confirm('确定打印?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const loading = this.getLoadingMask()
        autoCheck({
          data: JSON.stringify({
            head: this.formM,
            list: this.list
          })
        }).then(res => {
          // webPrint.openDevTools()
          console.log(res)
          loading.close()
          if (res.success) {
            webPrint.send('webview-print-render', res)
          } else {
            this.$notify({
              title: '提示',
              message: res.msg,
              duration: 0
            })
          }
        })
      })
    },
    getLoadingMask(text = '打印中') {
      return this.$loading({
        lock: true,
        text,
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
    },
    sendEmail() {
      this.$confirm('确定发送?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const loading = this.getLoadingMask('发送中')
        generateMessage({
          data: JSON.stringify({
            head: this.formM,
            list: this.list
          })
        }).then(res => {
          loading.close()
          if (res.success) {
            this.$message({
              message: '发送成功',
              type: 'success',
              center: true
            })
          } else {
            this.$notify({
              title: '提示',
              message: res.msg,
              duration: 0
            })
          }
        })
      })
    }
  }
}
</script>

<style rel='stylesheet/scss' lang='scss' >
 .el-table .cell, .el-table th div{
   padding: 0 2px !important;
 }
 .el-table td, .el-table th{
   padding: 0 !important;
 }
 .el-table th{
   background:#f3f5f8;
   color:#3b3b3b;
   font-weight:normal;
 }
 .row-table{
   border:1px solid #b0b6bc;
   .el-form-item{
     margin-bottom:0;
   }
 }
.el-input-number .el-input__inner{
  text-align: left;
}
 .tool-wrap{
   margin-bottom:5px;
 }

 .el-form-item--mini.el-form-item{
   margin-bottom:0;
 }

 .nowrap .cell{
   white-space: nowrap;
 }

 input:focus{
    outline: none;
    border-color: #4279F4;
    box-shadow: 0 0 10px #4279F4;
    //  background: #4279F4;
    // color: #fff;
 }
</style>

